package org.peterbjornx.io;

/**
 * Created by IntelliJ IDEA.
 * User: PeterbjornX
 * Date: Apr 10, 2009
 * Time: 10:52:25 AM
 * @author JAGeX,WinterLove,Graham,Moparisthebest
 * TODO: Write a non jagex based implementation
 */
public final class BitStream {

    public BitStream(byte abyte0[])
    {
        buffer = abyte0;
            pos = 0;
    }
    public BitStream(byte abyte0[],int spos)
    {
        buffer = abyte0;
        pos = spos;
    }


    public void initBitAccess()
    {
        bitPosition = pos * 8;
    }

    public int readBits(int i)
    {
        int k = bitPosition >> 3;
        int l = 8 - (bitPosition & 7);
        int i1 = 0;
        bitPosition += i;
        for(; i > l; l = 8)
        {
            i1 += (buffer[k++] & anIntArray1409[l]) << i - l;
            i -= l;
        }
        if(i == l)
            i1 += buffer[k] & anIntArray1409[l];
        else
            i1 += buffer[k] >> l - i & anIntArray1409[i];
        return i1;
    }

    public void finishBitAccess()
    {
        pos = (bitPosition + 7) / 8;
    }



    public byte buffer[];
    public int pos;
    public int bitPosition;
    private static final int[] anIntArray1409 = {
        0, 1, 3, 7, 15, 31, 63, 127, 255, 511,
        1023, 2047, 4095, 8191, 16383, 32767, 65535, 0x1ffff, 0x3ffff, 0x7ffff,
        0xfffff, 0x1fffff, 0x3fffff, 0x7fffff, 0xffffff, 0x1ffffff, 0x3ffffff, 0x7ffffff, 0xfffffff, 0x1fffffff,
        0x3fffffff, 0x7fffffff, -1
    };

    public int readByte() {
        return buffer[pos++] & 0xff;
    }

    public int readShortLittleEndian() {
        return readByte() + (readByte() << 8);
    }
    public void readBytes_reverse(byte abyte0[], int len, int off) {
		for (int p = (off + len) - 1; p >= off; p--)
			abyte0[p] = buffer[pos++];

	}
    public void readBytes(byte abyte0[], int len, int off) {
		for (int k = off; k < off + len; k++)
			abyte0[k] = buffer[pos++];

	}
    public int readByteC()
    {
        return -buffer[pos++] & 0xff;
    }
}

